package com.rzico.quartz.job;

import com.alibaba.fastjson.JSON;
import com.rzico.account.entity.Refunds;
import com.rzico.account.model.Attach;
import com.rzico.core.entity.SysJob;
import com.rzico.core.service.SysJobService;
import com.rzico.core.service.SysPvuvSummaryService;
import com.rzico.core.service.SysSequenceService;
import com.rzico.order.entity.GroupBuy;
import com.rzico.order.entity.GroupPeriod;
import com.rzico.order.entity.Order;
import com.rzico.order.service.GroupBuyService;
import com.rzico.order.service.GroupOrderService;
import com.rzico.order.service.GroupPeriodService;
import com.rzico.order.service.OrderService;
import com.rzico.util.RedisHandler;
import org.apache.commons.lang3.time.DateUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by zhongzm on 2020/2/2.
 * 计划任务执行demo
 */
public class GroupBuyRobot implements Job {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    protected SysPvuvSummaryService sysPvuvSummaryService;

    @Autowired
    protected SysJobService sysJobService;

    @Autowired
    protected SysSequenceService sysSequenceService;

    @Autowired
    protected GroupBuyService groupBuyService;

    @Autowired
    protected GroupOrderService groupOrderService;

    @Autowired
    protected GroupPeriodService groupPeriodService;

    @Autowired
    private RedisHandler redisHandler;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String jobId = jobExecutionContext.getTrigger().getKey().getName();
        SysJob sysJob = sysJobService.selectByPrimaryKey(jobId);
        try {
            if (sysJob.getExecStatus().equals(1)) {
                //不能重复执行
                return;
            }
            sysJob.setExecStatus(1);
            sysJob.setJobDesc("开始执行:"+sdf.format(new Date()));
            sysJobService.updateByPrimaryKeySelective(sysJob);

            // 这里开始查询5分钟时查一次,1.处理已完成本期周期团购 2.对
            //   TODO

            Map<String,Object> params = new HashMap<>();
            params.put("status",1);
            List<GroupBuy> groupBuyList = groupBuyService.selectList(params);
            for (GroupBuy groupBuy:groupBuyList) {

                try {
                    if (groupBuy.getPeriodId()!=null && groupBuy.getStatus().equals(1)) {
                        GroupPeriod groupPeriod = groupPeriodService.selectByPrimaryKey(groupBuy.getPeriodId());
                        Date c = groupPeriod.getCreateDate();
                        c = DateUtils.addMinutes(c, groupBuy.getDuration());
                        if (c.before(new Date())) {
                            //过期团购，参机人参与
                            groupOrderService.addRobot(groupBuy.getId());
                        }
                    }

                } catch (Exception e) {
                    logger.error(e.getMessage());
                }

            }
            // end

            params.clear();
            params.put("status",1);
            List<GroupPeriod> groupPeriodList = groupPeriodService.selectList(params);
            for (GroupPeriod groupPeriod:groupPeriodList) {

                try {
                    String sn = "GP"+String.valueOf(groupPeriod.getId());
                    List<Refunds> refundsList = groupOrderService.newPeriod(groupPeriod.getGroupBuyId(),sn);
                    for (Refunds refunds:refundsList) {
                        //TODO发送退款通知
                        Attach attachQueue = new Attach();
                        attachQueue.setCode("0000");
                        attachQueue.setId(String.valueOf(refunds.getId()));
                        attachQueue.setQueue("queue.refunds.submit");
                        Message message = MessageBuilder
                                .withBody(JSON.toJSONString(attachQueue).getBytes())
                                .setContentType(MessageProperties.CONTENT_TYPE_JSON)
                                .build();
                        CorrelationData correlationData = new CorrelationData();
                        correlationData.setId(UUID.randomUUID().toString());
                        logger.info("发送 MQ");
                        rabbitTemplate.convertAndSend("directExchange",attachQueue.getQueue()+".key", message, correlationData);

                    }
                } catch (Exception e) {
                    logger.error(e.getMessage());
                }

            }


            for (GroupBuy groupBuy:groupBuyList) {

                try {

                    if (groupBuy.getEndDate().before(new Date())) {
                        List<Refunds> refundsList = groupBuyService.cancel(groupBuy);
                        for (Refunds refunds:refundsList) {
                            //TODO发送退款通知
                            Attach attachQueue = new Attach();
                            attachQueue.setCode("0000");
                            attachQueue.setId(String.valueOf(refunds.getId()));
                            attachQueue.setQueue("queue.refunds.submit");
                            Message message = MessageBuilder
                                    .withBody(JSON.toJSONString(attachQueue).getBytes())
                                    .setContentType(MessageProperties.CONTENT_TYPE_JSON)
                                    .build();
                            CorrelationData correlationData = new CorrelationData();
                            correlationData.setId(UUID.randomUUID().toString());
                            logger.info("发送 MQ");
                            rabbitTemplate.convertAndSend("directExchange",attachQueue.getQueue()+".key", message, correlationData);
                        }
                    }

                } catch (Exception e) {
                    logger.error(e.getMessage());
                }

            }

            sysJob.setExecStatus(0);
            sysJob.setJobDesc("执行成功:"+sdf.format(new Date())+",下次执行:"+sdf.format(jobExecutionContext.getNextFireTime()));
            sysJobService.updateByPrimaryKeySelective(sysJob);
        }
        catch (Exception e) {
            sysJob.setExecStatus(0);
            sysJob.setJobDesc("执行错误:"+sdf.format(new Date()));
            sysJobService.updateByPrimaryKeySelective(sysJob);
        }

    }
}
